package com.example.educational.controller.utils;

import cn.hutool.core.util.ObjectUtil;
import com.example.educational.entity.User;
import com.example.educational.service.CorporateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


/**
 * 表现成项目拦截器，当所有的请求进入后台时，会被词类进行拦截认证
 * 认证的主要内容：1.验证数据Code
 */
@Slf4j
public class ProjectInterceptor implements HandlerInterceptor {

    @Autowired
    CorporateService corporateService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        // 1.数据验证
        String code = request.getHeader("code");
        if (ObjectUtil.isNull(code) || ObjectUtil.equal(code, "")) {
            log.info("请求Code不能为空！！！");
            throw new BusinessException(Code.err, "请求Code不能为空！！！"); // 若请求异常则响应用户操作错误异常
        }
        // 2.验证用户信息 - code验证
        User user = corporateService.checkUserIdentify(code);
        if (Objects.equals(user.getId(), null)) {
            //用户不存在，验证失败
            log.info("用户验证失败，请重新查看！！！");
            throw new BusinessException(Code.err, "服务器忙，请稍后再试"); // 若请求异常则响应用户操作错误异常
        } else {
            //用户存在，转发用户信息到request域中
            log.info("用户验证成功~");
            request.setAttribute("user", user);
        }
        return Boolean.TRUE;
    }
}
